package com.davy.gridpoint.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.ScreenManager;
import com.davy.gridpoint.adapter.PointListAdapter;
import com.davy.gridpoint.adapter.SourceAdapter;
import com.davy.gridpoint.bean.ChooseBean;
import com.davy.gridpoint.http.CommonHttpConsts;
import com.davy.gridpoint.http.HttpCallbackData;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.http.JsonBeanData;
import com.davy.gridpoint.utils.DeviceIdHelper;
import com.davy.gridpoint.utils.DialogUitl;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.SPUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.IndicatorProgressBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

public class PointListActivity extends BaseActivity {
    private long mExitTime = 0;//退出程序
    private TextView tvSelect;
    private LinearLayout lyNoLayout;
    private RecyclerView mXRecyclerView;
    private PointListAdapter listAdapter;
    private ArrayList<Map> dataList;
    private EditText etSearch;
    private ImageView imgClear;
    private String strSelect = "";
    private String pwsSelect = "";
    private ArrayList<ChooseBean> stationList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pointlist);
        statusbar4();
        strSelect = SPUtils.get(mContext, "strSelect", "") + "";
        pwsSelect = SPUtils.get(mContext, "pwsSelect", "") + "";
        LogUtils.e("TAG", "pwsSelect" + pwsSelect);
        initView();
        initData();
        String insertTime = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(insertTime)) {
            upLogInfo(insertTime);
        }
        initClick();
    }

    private void initData() {
        ChooseBean chooseBean1 = new ChooseBean();
        chooseBean1.setName("西安铁路局");
        chooseBean1.setPid("lj0001");
        ChooseBean chooseBean2 = new ChooseBean();
        chooseBean2.setName("西安工务段");
        chooseBean2.setPid("pws001");
        ChooseBean chooseBean3 = new ChooseBean();
        chooseBean3.setName("宝鸡工务段");
        chooseBean3.setPid("pws002");
        ChooseBean chooseBean4 = new ChooseBean();
        chooseBean4.setName("安康工务段");
        chooseBean4.setPid("pws003");
        ChooseBean chooseBean5 = new ChooseBean();
        chooseBean5.setName("汉中工务段");
        chooseBean5.setPid("pws004");
        ChooseBean chooseBean6 = new ChooseBean();
        chooseBean6.setName("阎良工务段");
        chooseBean6.setPid("pws005");
        ChooseBean chooseBean7 = new ChooseBean();
        chooseBean7.setName("延安工务段");
        chooseBean7.setPid("pws006");
        ChooseBean chooseBean8 = new ChooseBean();
        chooseBean8.setName("绥德工电段");
        chooseBean8.setPid("pws008");
        ChooseBean chooseBean9 = new ChooseBean();
        chooseBean9.setName("西安高铁基础设施段");
        chooseBean9.setPid("pws009");
        ChooseBean chooseBean10 = new ChooseBean();
        chooseBean10.setName("延安运营维修段");
        chooseBean10.setPid("pws010");
        ChooseBean chooseBean11 = new ChooseBean();
        chooseBean11.setName("西安电务段");
        chooseBean11.setPid("pws011");
        ChooseBean chooseBean12 = new ChooseBean();
        chooseBean12.setName("宝鸡电务段");
        chooseBean12.setPid("pws012");
        ChooseBean chooseBean13 = new ChooseBean();
        chooseBean13.setName("安康电务段");
        chooseBean13.setPid("pws013");
        ChooseBean chooseBean14 = new ChooseBean();
        chooseBean14.setName("西安通信段");
        chooseBean14.setPid("pws015");
        ChooseBean chooseBean15 = new ChooseBean();
        chooseBean15.setName("西安供电段");
        chooseBean15.setPid("pws017");
        ChooseBean chooseBean16 = new ChooseBean();
        chooseBean16.setName("宝鸡供电段");
        chooseBean16.setPid("pws018");
        ChooseBean chooseBean17 = new ChooseBean();
        chooseBean17.setName("安康供电段");
        chooseBean17.setPid("pws019");
        ChooseBean chooseBean18 = new ChooseBean();
        chooseBean18.setName("西安车务段");
        chooseBean18.setPid("pws021");
        ChooseBean chooseBean19 = new ChooseBean();
        chooseBean19.setName("宝鸡车务段");
        chooseBean19.setPid("pws022");
        ChooseBean chooseBean20 = new ChooseBean();
        chooseBean20.setName("安康车务段");
        chooseBean20.setPid("pws023");
        ChooseBean chooseBean21 = new ChooseBean();
        chooseBean21.setName("汉中车务段");
        chooseBean21.setPid("pws024");
        ChooseBean chooseBean22 = new ChooseBean();
        chooseBean22.setName("铜川车务段");
        chooseBean22.setPid("pws025");
        ChooseBean chooseBean23 = new ChooseBean();
        chooseBean23.setName("韩城车务段");
        chooseBean23.setPid("pws026");
        ChooseBean chooseBean24 = new ChooseBean();
        chooseBean24.setName("延安车务段");
        chooseBean24.setPid("pws027");
        ChooseBean chooseBean25 = new ChooseBean();
        chooseBean25.setName("西安客运段");
        chooseBean25.setPid("pws028");
        ChooseBean chooseBean26 = new ChooseBean();
        chooseBean26.setName("新丰镇机务段");
        chooseBean26.setPid("pws029");
        ChooseBean chooseBean27 = new ChooseBean();
        chooseBean27.setName("西安机务段");
        chooseBean27.setPid("pws030");
        ChooseBean chooseBean28 = new ChooseBean();
        chooseBean28.setName("安康机务段");
        chooseBean28.setPid("pws031");
        ChooseBean chooseBean29 = new ChooseBean();
        chooseBean29.setName("延安机务段");
        chooseBean29.setPid("pws032");
        ChooseBean chooseBean30 = new ChooseBean();
        chooseBean30.setName("西安车站");
        chooseBean30.setPid("pws033");
        ChooseBean chooseBean31 = new ChooseBean();
        chooseBean31.setName("安康东站");
        chooseBean31.setPid("pws034");
        ChooseBean chooseBean32 = new ChooseBean();
        chooseBean32.setName("西安西站");
        chooseBean32.setPid("pws035");
        ChooseBean chooseBean33 = new ChooseBean();
        chooseBean33.setName("新丰镇车站");
        chooseBean33.setPid("pws036");
        ChooseBean chooseBean34 = new ChooseBean();
        chooseBean34.setName("宝鸡东站");
        chooseBean34.setPid("pws037");
        ChooseBean chooseBean35 = new ChooseBean();
        chooseBean35.setName("西安房建公寓段");
        chooseBean35.setPid("pws038");
        ChooseBean chooseBean36 = new ChooseBean();
        chooseBean36.setName("安康房建公寓段");
        chooseBean36.setPid("pws039");
        ChooseBean chooseBean37 = new ChooseBean();
        chooseBean37.setName("工务机械段");
        chooseBean37.setPid("pws046");

//        stationList.add(chooseBean1);
        stationList.add(chooseBean2);
        stationList.add(chooseBean3);
        stationList.add(chooseBean4);
        stationList.add(chooseBean5);
        stationList.add(chooseBean6);
        stationList.add(chooseBean7);
        stationList.add(chooseBean8);
        stationList.add(chooseBean9);
        stationList.add(chooseBean10);

//        stationList.add(chooseBean11);
//        stationList.add(chooseBean12);
//        stationList.add(chooseBean13);
//        stationList.add(chooseBean14);
//        stationList.add(chooseBean15);
//        stationList.add(chooseBean16);
//        stationList.add(chooseBean17);
//        stationList.add(chooseBean18);
//        stationList.add(chooseBean19);
//        stationList.add(chooseBean20);
//
//        stationList.add(chooseBean21);
//        stationList.add(chooseBean22);
//        stationList.add(chooseBean23);
//        stationList.add(chooseBean24);
//        stationList.add(chooseBean25);
//        stationList.add(chooseBean26);
//        stationList.add(chooseBean27);
//        stationList.add(chooseBean28);
//        stationList.add(chooseBean29);
//        stationList.add(chooseBean30);
//
//        stationList.add(chooseBean31);
//        stationList.add(chooseBean32);
//        stationList.add(chooseBean33);
//        stationList.add(chooseBean34);
//        stationList.add(chooseBean35);
//        stationList.add(chooseBean36);
//        stationList.add(chooseBean37);
    }

    private void initView() {
        dataList = new ArrayList<>();
        stationList = new ArrayList<>();
        tvSelect = findViewById(R.id.tvSelect);
        if (StringUtils.isEmpty(strSelect)) {
            tvSelect.setText("请选择工务段");
            tvSelect.setTextColor(mContext.getResources().getColor(R.color.orange_salmon));
        } else {
            tvSelect.setText(strSelect);
            tvSelect.setTextColor(mContext.getResources().getColor(R.color.white));
        }

        mXRecyclerView = findViewById(R.id.mXRecyclerView);
        lyNoLayout = findViewById(R.id.lyNoLayout);
        lyNoLayout.setVisibility(View.VISIBLE);
        etSearch = findViewById(R.id.etSearch);
        imgClear = findViewById(R.id.imgClear);
        imgClear.setVisibility(View.GONE);

        destfiledir = Environment.getExternalStorageDirectory().getPath();
        LogUtils.e("tag", "destfiledir:" + destfiledir);
        mProgress = findViewById(R.id.update_progress);
        rl_softu = findViewById(R.id.rl_softu);
        lyDialog = findViewById(R.id.lyDialog);
        tvContext = findViewById(R.id.tvContext);
        tvDialogCancel = findViewById(R.id.tvDialogCancel);
        tvDialogConfirm = findViewById(R.id.tvDialogConfirm);
        rl_softu.setVisibility(View.GONE);
        rl_softu.setOnClickListener(v -> {
        });
        lyDialog.setOnClickListener(v -> {
        });

        tvDialogCancel.setOnClickListener(v -> lyDialog.setVisibility(View.GONE));
        tvDialogConfirm.setOnClickListener(v -> {
            lyDialog.setVisibility(View.GONE);
            rl_softu.setVisibility(View.VISIBLE);
            downloadNewFile();
        });

        upVersions();

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false);
        mXRecyclerView.setLayoutManager(layoutManager);
        listAdapter = new PointListAdapter(mContext, dataList);
        mXRecyclerView.setAdapter(listAdapter);
        listAdapter.setItemClickListener((pos, mData) -> {
            if (StringUtils.isFastClick()) {
                return;
            }

            Intent intent = new Intent(mContext, PointActivity.class);
            intent.putExtra("dataMap", (Serializable) mData);
            startActivity(intent);
        });

        findViewById(R.id.tvTakePhoto).setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            startActivity(new Intent(mContext, GridActivity.class));
//            startActivity(new Intent(mContext, TakePhotoActivity.class));
        });

        RPCGetGeoGrids();
    }

    private void RPCGetGeoGrids() {
        LogUtils.e("TAG", "RPCGetGeoGrids" + pwsSelect);
        if (StringUtils.isEmpty(pwsSelect)) {
            ToastUtil.showNew(mContext, "请选择工务段");
            return;
        }

        HttpClient.getInstance().getData(CommonHttpConsts.RPCGetGeoGrids, "RPCGetGeoGrids")
                .tag(this)
                .params("pwsid", pwsSelect)
                .execute(new HttpCallbackData() {

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);

                        if (code == 200) {
                            if (!StringUtils.isEmpty(info)) {
                                String string = StringUtils.decompressForGzip(info);
                                LogUtils.e("TAG", "string:" + string);
                                dataList = (ArrayList<Map>) JSONArray.parseArray(string, Map.class);
                            }
                        } else {

                            ToastUtil.show(msg);
                        }

                        listAdapter.setData(dataList);
                        if (dataList.size() > 0) {
                            mXRecyclerView.setVisibility(View.VISIBLE);
                            lyNoLayout.setVisibility(View.GONE);
                        } else {
                            mXRecyclerView.setVisibility(View.GONE);
                            lyNoLayout.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.show(StringUtils.error_context);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
//                        mXRecyclerView.refreshComplete();
//                        mXRecyclerView.setPullRefreshEnabled(true);
                    }
                });
    }

    private void performSearch(String query) {
        StringUtils.hintKeyBoard(mContext, etSearch);
        ArrayList<Map> searchList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).get("GeoGridName").toString().contains(query)) {
                searchList.add(dataList.get(i));
            }
        }

        listAdapter.setData(searchList);
        if (searchList.size() > 0) {
            mXRecyclerView.setVisibility(View.VISIBLE);
            lyNoLayout.setVisibility(View.GONE);
        } else {
            mXRecyclerView.setVisibility(View.GONE);
            lyNoLayout.setVisibility(View.VISIBLE);
        }
    }

    private void initClick() {
        tvSelect.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) return;
            dismiss();
            if (stationList.size() == 0) {
                ToastUtil.show("没有工务段数据");
                return;
            }
            initPopupWindow(tvSelect, stationList);
        });
        lyNoLayout.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            RPCGetGeoGrids();
        });
        imgClear.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            etSearch.setText("");
            StringUtils.hintKeyBoard(mContext, etSearch);
            listAdapter.setData(dataList);
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean hasContent = s.length() > 0;
                if (hasContent) {
                    imgClear.setVisibility(View.VISIBLE);
                } else {
                    imgClear.setVisibility(View.GONE);
                }
            }
        });
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch(v.getText().toString());
                return true;
            }
            return false;
        });
    }

    private void upLogInfo(String insertTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", insertTime);
        jsonObject.put("imei", DeviceIdHelper.getDeviceId(mContext));
        jsonObject.put("loginfo", SPUtils.get(mContext, "benE", ""));
        jsonObject.put("versions", StringUtils.getVerName(mContext));
        jsonObject.put("uname", SPUtils.get(mContext, "userPhone", ""));

        LogUtils.e("TAG", "jsonObject--->" + jsonObject.toString());

        HttpClient.getInstance().post(HttpClient.httpUrl + CommonHttpConsts.upLogInfo, "upLogInfo").upJson(jsonObject.toString()).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200) {
                    SPUtils.put(mContext, "benE", "");
                    SPUtils.put(mContext, "benS", "");
                }
            }
        });
    }

    //系统升级
    private IndicatorProgressBar mProgress;
    private RelativeLayout rl_softu;
    private LinearLayout lyDialog;
    private TextView tvContext;
    private String destfiledir;
    private String downloadurl;
    private String app_name = "";
    private TextView tvDialogCancel, tvDialogConfirm;
    private int isforcedupdate = 0;

    private void upVersions() {
        HttpClient.getInstance().getData(CommonHttpConsts.upVersion, "upVersion").params("version", StringUtils.getVerName(mContext)).params("railway", "wangge").execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200 && !StringUtils.isEmpty(info)) {
                    String string = StringUtils.decompressForGzip(info);
                    Map dataMap = JSON.parseObject(string, Map.class);
                    if (dataMap.size() > 0) {
                        downloadurl = dataMap.get("url") + "";
                        app_name = dataMap.get("name") + "";
                        tvContext.setText(dataMap.get("content") + "");
                        String isfo = dataMap.get("force") + "";
                        if (!StringUtils.isEmpty(isfo)) {
                            isforcedupdate = Integer.valueOf(isfo);
                        }
                        lyDialog.setVisibility(View.VISIBLE);
                        if (isforcedupdate == 1) {
                            tvDialogCancel.setVisibility(View.GONE);
                        } else {
                            tvDialogCancel.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
//                            ToastUtil.show(msg);
                }
            }

            @Override
            public void onError(Response<JsonBeanData> response) {
                super.onError(response);
                ToastUtil.show(StringUtils.error_context);
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void downloadNewFile() {
        OkGo.<File>get(downloadurl).tag(mContext).execute(new FileCallback(destfiledir, app_name) {
            @Override
            public void onSuccess(Response<File> response) {
                String s = destfiledir + "/" + app_name;
                rl_softu.setVisibility(View.GONE);
                installApk(s);
            }


            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                LogUtils.e("TAG", "下载进度：" + (int) (progress.fraction * 100));
                mProgress.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                runOnUiThread(() -> {
                    rl_softu.setVisibility(View.GONE);
                    ToastUtil.show("网络中断，请稍后再试！");
                });
            }
        });
    }

    /**
     * 安装apk
     */
    public void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            ToastUtil.show("更新失败！未找到安装包");
            return;
        }

        LogUtils.e("TAG", "开始执行安装: " + apkPath);
        File apkFile = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("TAG", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.davy.gridpoint.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            LogUtils.e("TAG", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    private PopupWindow popupWindow;

    private void initPopupWindow(View data, ArrayList<ChooseBean> popList) {
        View view = View.inflate(mContext, R.layout.layout_popup_view, null);
        RecyclerView recyclerPop = view.findViewById(R.id.recyclerPop);
        recyclerPop.setLayoutManager(new LinearLayoutManager(mContext));
        SourceAdapter sourceAdapter = new SourceAdapter(mContext, popList);
        recyclerPop.setAdapter(sourceAdapter);
        popupWindow = new PopupWindow(view, 500, ViewGroup.LayoutParams.WRAP_CONTENT);

        view.setBackgroundColor(mContext.getResources().getColor(R.color.tv6060));
        // 设置PopupWindow的遮罩层颜色
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 点击框外可以使得popupwindow消失
        popupWindow.setFocusable(true);
        //设置可以触摸弹出框以外的区域
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(data, 0, 0);
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        sourceAdapter.setOnItemClickListener((position, string) -> {
            tvSelect.setText(string.getName());
            stationList.get(0).setType(position);

            strSelect = string.getName();
            pwsSelect = string.getPid();

            RPCGetGeoGrids();

            SPUtils.put(mContext, "strSelect", strSelect);
            SPUtils.put(mContext, "pwsSelect", pwsSelect);
            dismiss();
        });
    }

    private void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
